//
//  AppDelegate.m
//  QRMaster
//
//  Created by myApple on 15/11/9.
//  Copyright (c) 2015年 myApple. All rights reserved.
//

#import "AppDelegate.h"
#import "RequestNetWork.h"
#import "QRNavigationController.h"
#import "QRTabbarController.h"
#import "StartPageController.h"
#import <ShareSDK/ShareSDK.h>
#import "WXApi.h"
#import <TencentOpenAPI/QQApiInterface.h>
#import <TencentOpenAPI/TencentOAuth.h>
#import "OpertionPlist.h"
#import "InternationalControl.h"
#import "GuadeController.h"
#import "GesturePasswordController.h"
#import "QRTabbarController.h"
#import "KeychainItemWrapper.h"
#import "CommunityListInfo.h"
#import "GesturePasswordView.h"
#import "faveriterCard.h"
#import "Base64.h"
#import "SKPSMTPMessage.h"
#import "UncaughtExceptionHandler.h"
#import "checkPower.h"

@interface AppDelegate ()<VerificationDelegate,ResetDelegate,GesturePasswordDelegate>
{
    QRNavigationController *nav;
    NSUserDefaults * userInfo;
    NSString * password;
    GesturePasswordView * gestureView;
    NSInteger count;
    NSString * VersionString;//当前版本号
}
@property (nonatomic,strong)QRTabbarController *tabbarController;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(startUp:) name:@"startUp"object:nil];
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    [self performSelectorInBackground:@selector(initDataBase)
                           withObject:nil];
    // Override point for customization after application launch.
    [NSThread sleepForTimeInterval:1.0];
//    InstallUncaughtExceptionHandler();
//    _tokeFlag = YES;
//    _notificationTimes = 1;//表示第一次
    //获取系统当前语言，如果没有系统的语言就默认英语
    [InternationalControl initUserLanguage];
    userInfo = [NSUserDefaults standardUserDefaults];
    [QRSingleton sharedQRSingleton].communityId = [[NSUserDefaults standardUserDefaults] objectForKey:@"communityId"];
//    if ([QRSingleton sharedQRSingleton].communityId != nil) {
//        //如果有集群则需要请求角色
//        checkPower * power = [[checkPower alloc]init];
//        [power getUserPower];
//        power.powerBlock = ^(id data,id error)
//        {
//            if ([data objectForKey:@"data"])
//            {
//                NSDictionary * communtiyDict = [data objectForKey:@"data"];
//                NSArray * CommunityArray = [communtiyDict objectForKey:@"communities"];
//                for (NSDictionary * dict in CommunityArray)
//                {
//                    if ([[dict objectForKey:@"communityid"]isEqualToString:[QRSingleton sharedQRSingleton].communityId])
//                    {
//                        [QRSingleton sharedQRSingleton].roleIndex = [[dict objectForKey:@"role"]integerValue];
//                    }
//                }
//                
//            }
//        };
//    }
    CommunityListInfo * comListInfo = [[CommunityListInfo alloc]init];
    [comListInfo queryCommunityName:[QRSingleton sharedQRSingleton].communityId block:^(NSString *communityName) {
        [QRSingleton sharedQRSingleton].communityName = communityName;
    }];
    //版本来改变收藏房卡
    if (!BeforeVersion) {
        VersionString = [NSString stringWithFormat:@"%@",[[[NSBundle mainBundle]infoDictionary]objectForKey:@"CFBundleShortVersionString"]];
        [userInfo setObject:VersionString forKey:@"beforeVersion"];
         [self getFaveriterCard];
//        [self performSelectorInBackground:@selector(initDataBase)
//                               withObject:nil];
    }
//    else
//    {
//          [self initDataBase];
//        VersionString = [NSString stringWithFormat:@"%@",[[[NSBundle mainBundle]infoDictionary]objectForKey:@"CFBundleShortVersionString"]];
//        NSComparisonResult resultInteger = [BeforeVersion compare:VersionString options:NSNumericSearch];
//        if (resultInteger == -1) {
//            [self performSelectorInBackground:@selector(initDataBase)
//                                   withObject:nil];
//        }
//    }
    /*
     客户那里房间号和集群不匹配的解决方法
     */
    NSMutableDictionary * data = [OpertionPlist readDataFromPlist];
    [data setValue:nil forKey:HOUSEINFO];
    [OpertionPlist writeDataToPlist:data];
    if (![[NSUserDefaults standardUserDefaults]boolForKey:@"firstLaunch"]) {
        [userInfo setValue:@"yes" forKey:@"middle"];//快捷按钮提示操作
        [userInfo setValue:@"yes" forKey:@"share"];//分享按钮提示操作
        [userInfo setValue:@"yes" forKey:@"setlock"];//授权分配卡切换提示操作
        [userInfo setValue:@"yes" forKey:@"faverit"];//收藏房卡提示操作
        [userInfo setValue:@"yes" forKey:@"address"];//从通讯录添加成员
        [userInfo setValue:@"yes" forKey:@"changeCommunity"];//切换集群提示操作
        [userInfo setValue:@"yes" forKey:@"longPress"];//长按分享的按钮
        [userInfo setValue:@"1" forKey:@"sound"];//声音开关
        GuadeController * SPG = [[GuadeController alloc]init];
        nav=[[QRNavigationController alloc]initWithRootViewController:SPG];
        self.window.rootViewController = nav;
    }
    else if ([[userInfo objectForKey:@"login"]isEqualToString:@"logined"])//是退出还是后台关闭应用
    {
        //后台关闭应用
        if([self exist])//是否存在手势密码
        {
            if([[userInfo objectForKey:@"gesture"] isEqualToString:@"1"])//标示手势密码状态是打开
            {
                GesturePasswordController * gpc = [[GesturePasswordController alloc]init];
                gpc.comein = @"first";
                nav=[[QRNavigationController alloc]initWithRootViewController:gpc];
                self.window.rootViewController = nav;
                //通过block传值来进入登录页面
                gpc.GoStartPage = ^(NSString * gostartpage)
                {
                    //判断是否点击了忘记密码
                    if ([gostartpage isEqualToString:@"yes"]) {
                        StartPageController * SPG = [[StartPageController alloc]init];
                        nav=[[QRNavigationController alloc]initWithRootViewController:SPG];
                        self.window.rootViewController = nav;
                    }
                };
                
            }
            else
            {
                QRTabbarController *qr=[[QRTabbarController alloc]init];
//                nav=[[QRNavigationController alloc]initWithRootViewController:qr];
//                nav.navigationBarHidden = YES;
                self.window.rootViewController = qr;
            }
            
        }
        else
        {
            //默认直接进入主界面
            QRTabbarController *qr=[[QRTabbarController alloc]init];
            nav=[[QRNavigationController alloc]initWithRootViewController:qr];
            nav.navigationBarHidden = YES;
            self.window.rootViewController=nav;
        }

    }
    else
    {
//        点击退出  退出应用
        StartPageController * SPG = [[StartPageController alloc]init];
        nav=[[QRNavigationController alloc]initWithRootViewController:SPG];
        self.window.rootViewController = nav;
    }

    
    [ShareSDK registerApp:ShareSDKSecretKey];
    
    //添加QQ应用
    [ShareSDK connectQQWithQZoneAppKey:ShareQZoneIDKey
                     qqApiInterfaceCls:[QQApiInterface class]
                       tencentOAuthCls:[TencentOAuth class]];
    
    //添加微信应用
    [ShareSDK connectWeChatWithAppId:ShareWeChatIDKey
                           appSecret:ShareWeChatSecretKey
                           wechatCls:[WXApi class]];
    //添加短信
    [ShareSDK connectSMS];
    
    /*
     网络监控,假设当前是wifi
     */
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(netWorkChanged:) name:kReachabilityChangedNotification object:nil];
    //目前网络状态
    _reachability = [Reachability reachabilityWithHostName: @"www.baidu.com"];
    self.networkStatus = _reachability.currentReachabilityStatus;
    [_reachability startNotifier];
    
    
    [self.window makeKeyAndVisible];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    
    return YES;
}


#pragma mark - 判断是否已存在手势密码
- (BOOL)exist{
    password = [userInfo objectForKey:GUESTUREKEY];
    if ([password isEqualToString:@""] || password == nil)return NO;
    return YES;
}

-(void)netWorkChanged:(NSNotification *)not
{
    Reachability * curReach = [not object];
    NSParameterAssert([curReach isKindOfClass:[Reachability class]]);
    self.networkStatus = [curReach currentReachabilityStatus];
    if(_networkStatus == NotReachable)
    {
        [PromptInfoView showMessage:NSLocalizedString(@"checkBreakNetWork", nil)];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"netWorkBreak" object:nil];
    }
    else
    {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"netWorkJion" object:nil];
    }
}
-(void)startUp:(NSNotification *)not
{
    [userInfo setValue:nil forKey:@"login"];
    NSMutableDictionary * data = [OpertionPlist readDataFromPlist];
    [data setValue:nil forKey:HOUSEINFO];
    [data setValue:nil forKey:STAFFINFO];
    [data setValue:nil forKey:FAVERITCARD];
    [data setValue:nil forKey:COMMUNITYINFOFORKEY];
    QRSingleton * singleton = [QRSingleton sharedQRSingleton];
    [singleton singleRelease];
    singleton = nil;
    [OpertionPlist writeDataToPlist:data];
    GesturePasswordController * gpc = [[GesturePasswordController alloc]init];
    [gpc clear];
    [userInfo setValue:@"0" forKey:@"gesture"];
    StartPageController *start = [[StartPageController alloc]init];
    nav=[[QRNavigationController alloc]initWithRootViewController:start];
    self.window.rootViewController = nav;
    if ([@"288"isEqualToString:[not.object objectForKey:@"startUp"]]) {
        [PromptInfoView showMessage:NSLocalizedString(@"errorToken", nil)];
    }
}

#pragma mark -- 获取网络收藏房卡信息
-(void)getFaveriterCard
{
    if ([self IsHaveNetwork]) {
        return;
    }
    RequestNetWork * rnk = [[RequestNetWork alloc]init];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [rnk initWithPath:POST(GETCOLLECTROOM) params:postDict block:^(id downLoadData, id error) {
        if ([downLoadData objectForKey:@"data"] != nil) {
            [faveriterCard writeFaveriterCard:[downLoadData objectForKey:@"data"]];
        }
    }];
    
}


- (void)applicationWillResignActive:(UIApplication *)application {
    if ([UIScreen mainScreen].brightness == 1) {
        [[UIScreen mainScreen] setBrightness:0.5];
    }
    if (gestureView) {
        [gestureView removeFromSuperview];
    }
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    count = 5;
    if ([[userInfo objectForKey:@"guestureCount"]isEqualToString:@"1"])
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"KCHiddenKeyBoardNotification" object:nil];
        if([self exist])//是否存在手势密码
        {
            //手势密码时  不能够摇一摇
            [[NSNotificationCenter defaultCenter]postNotificationName:@"KCShakeSound" object:@"no"];
            if([[userInfo objectForKey:@"gesture"] isEqualToString:@"1"])//标示手势密码状态是打开
            {
                [self verify];
            }
        }
        
    }

}

- (void)verify{
    gestureView = [[GesturePasswordView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    [gestureView.tentacleView setRerificationDelegate:self];
    [gestureView.tentacleView setStyle:1];
    [gestureView setGesturePasswordDelegate:self];
    gestureView.hiddenOrNot = YES;
    [self.window addSubview:gestureView];
}

#pragma mark ----------------- 点击忘记密码
-(void)forget
{
    StartPageController * SPG = [[StartPageController alloc]init];
    nav=[[QRNavigationController alloc]initWithRootViewController:SPG];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"KCShakeSound" object:@"yes"];
    self.window.rootViewController = nav;
    [gestureView removeFromSuperview];
}

#pragma mark --------------- 检测手势密码
- (BOOL)verification:(NSString *)result{
    
    if ([result isEqualToString:password]) {
        [gestureView.state setTextColor:[UIColor colorWithRed:2/255.f green:174/255.f blue:240/255.f alpha:1]];
        [gestureView.state setText:NSLocalizedString(@"inputGuestureSuccess", nil)];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"KCShakeSound" object:@"yes"];
         gestureView.hidden = YES;
        [gestureView removeFromSuperview];
        return YES;
    }
    count --;
    if (count == 0) {
        StartPageController * SPG = [[StartPageController alloc]init];
        nav=[[QRNavigationController alloc]initWithRootViewController:SPG];
        self.window.rootViewController = nav;
        [userInfo setObject:nil forKey:@"login"];
        [userInfo setObject:@"0" forKey:@"gesture"];
        [self clear];
        NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
        [postDict setValue:@"logout" forKey:@"startUp"];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"startUp" object:postDict];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"KCShakeSound" object:@"yes"];
    }
    [gestureView.state setTextColor:[UIColor redColor]];
    NSString * locaStringOne = NSLocalizedString(@"guestureError", nil);
    NSString * locaStringTwo = NSLocalizedString(@"guestureChange", nil);
    [gestureView.state setText:[NSString stringWithFormat:@"%@%ld%@",locaStringOne,(long)count,locaStringTwo]];
    return NO;
}



#pragma mark - 清空记录
- (void)clear{
    [userInfo setValue:@"" forKey:GUESTUREKEY];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return [ShareSDK handleOpenURL:url wxDelegate:self];
}

-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    return [ShareSDK handleOpenURL:url sourceApplication:sourceApplication annotation:annotation wxDelegate:self];
}

//写入数据库
- (void)initDataBase
{
    [self deleteDataBase];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documents = [paths objectAtIndex:0];
    NSString *database_path = [documents stringByAppendingPathComponent:@"ma_db.db"];
    NSData *data = [NSData dataWithContentsOfFile:database_path];
    if (data == nil) {
        NSString *dbStr = [[NSBundle mainBundle] pathForResource:@"ma_db" ofType:@"db"];
        NSData *dbData = [NSData dataWithContentsOfFile:dbStr];
        
        [dbData writeToFile:database_path atomically:YES];
    }
}

#pragma mark ------删除原先的数据库表
-(void)deleteDataBase
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documents = [paths objectAtIndex:0];
    NSString *database_path = [documents stringByAppendingPathComponent:@"masterss_db.db"];
//qrn_db.db
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    BOOL bRet = [fileMgr fileExistsAtPath:database_path];
    if (bRet) {
        //
        NSError *err;
        [fileMgr removeItemAtPath:database_path error:&err];
    }
}

//判断是否有网络
-(BOOL)IsHaveNetwork
{
    Reachability * reach = [Reachability reachabilityForInternetConnection];
    if([reach currentReachabilityStatus] == NotReachable) {
        [PromptInfoView showMessage:NSLocalizedString(@"noNetWork", nil)];
        return YES;
    }
    return NO;
}

@end
